package com.qubyer.okhttputil.builder;

import com.qubyer.okhttputil.request.PostFormRequest;
import com.qubyer.okhttputil.request.RequestCall;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

/**
 * Created by zhy on 15/12/14.
 */
public class PostFormBuilder extends OkHttpRequestBuilder<PostFormBuilder> {
    private List<FileInput> files = new ArrayList<>();
    private final String salt = "qumaimai20201215";
    @Override
    public RequestCall build() {
        if(params == null){
            params = new TreeMap<>();
        }
        params.put("timestamp", String.valueOf(System.currentTimeMillis()).substring(0,10));
        Set<Map.Entry<String, String>> entries = params.entrySet();
        Iterator<Map.Entry<String, String>> iterator = entries.iterator();
        StringBuilder stringBuilder = new StringBuilder();
        while (iterator.hasNext()) {
            Map.Entry<String, String> entry = iterator.next();
            stringBuilder.append(entry.getKey());
            stringBuilder.append("=");
            stringBuilder.append(entry.getValue());
            stringBuilder.append("&");
        }
        String s = stringBuilder.toString();
        if (s.length() > 0) {
            s = s.substring(0, s.length() - 1);
        }
        s += salt;
        String sign = MD5(s).toUpperCase();
        params.put("sign",sign);
        return new PostFormRequest(url, tag, params, headers, files, id).build();
    }

    public static String MD5(String in) {
        byte[] hash;
        try {
            hash = MessageDigest.getInstance("MD5").digest(in.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("Huh, MD5 should be supported?", e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("Huh, UTF-8 should be supported?", e);
        }

        StringBuilder hex = new StringBuilder(hash.length * 2);
        for (byte b : hash) {
            if ((b & 0xFF) < 0x10) hex.append("0");
            hex.append(Integer.toHexString(b & 0xFF));
        }
        return hex.toString();
    }

    public PostFormBuilder files(String key, Map<String, File> files) {
        for (String filename : files.keySet()) {
            this.files.add(new FileInput(key, filename, files.get(filename)));
        }
        return this;
    }

    public PostFormBuilder addFile(String name, String filename, File file) {
        files.add(new FileInput(name, filename, file));
        return this;
    }

    public static class FileInput {
        public String key;
        public String filename;
        public File file;

        public FileInput(String name, String filename, File file) {
            this.key = name;
            this.filename = filename;
            this.file = file;
        }

        @Override
        public String toString() {
            return "FileInput{" +
                    "key='" + key + '\'' +
                    ", filename='" + filename + '\'' +
                    ", file=" + file +
                    '}';
        }
    }

    public PostFormBuilder params(Map<String, String> params) {
        if (this.params == null) {
            this.params = new TreeMap<>();
        }
        this.params.putAll(params);
        return this;
    }

    public PostFormBuilder addParams(String key, String val) {
        if (this.params == null) {
            params = new TreeMap<>();
        }
        params.put(key, val);
        return this;
    }
}
